import "@blocknote/core/fonts/inter.css";
import "@blocknote/mantine/style.css";
import { BlockNoteSchema, defaultBlockSpecs, filterSuggestionItems, insertOrUpdateBlock,locales } from "@blocknote/core";
import { BlockNoteView } from "@blocknote/mantine";
import { useCreateBlockNote,SuggestionMenuController,  getDefaultReactSlashMenuItems,  } from "@blocknote/react"; 
import { RiAlertFill } from "react-icons/ri";
import { Alert } from "./Blocks/Alert"; 
import useConvertFileToBase64 from "../../utils/convertFileToBase64"
import {  useEffect  } from "react";

import JSON5 from 'json5';

// 安全解析函数
// @ts-ignore
function safeParse(input) {
  try {
    // 预处理：修复常见格式问题
    const sanitized = input
      // 移除尾随逗号
      .replace(/,\s*]/g, ']')
      .replace(/,\s*}/g, '}')
      // 为属性名添加双引号
      .replace(/([{,]\s*)(\w+)(\s*:)/g, '$1"$2"$3');

    // 使用JSON5解析
    return JSON5.parse(sanitized);
  } catch (error) {
    console.error('解析失败:', error);
    return null;
  }
}
const schema = BlockNoteSchema.create({
    blockSpecs: {
      // Adds all default blocks.
      ...defaultBlockSpecs,
      // Adds the Alert block.
      alert: Alert,  
    },
  });
   
  // Slash menu item to insert an Alert block
  const insertAlert = (editor: typeof schema.BlockNoteEditor) => ({
    title: "Alert", //Alert
    onItemClick: () => {
      insertOrUpdateBlock(editor, {
        type: "alert",
      });
    },
    aliases: [
      "alert",
      "notification",
      "emphasize",
      "warning",
      "error",
      "info",
      "success",
    ],
    group: "Other",
    // @ts-ignore
    icon: <RiAlertFill />,
  });
 

  async function uploadFile(file: File) {
    if (!file) return;

    const body = new FormData();
    body.append("file", file); 
    if(file.type.includes("image")){ 
      const base64 = await useConvertFileToBase64(file); 
      return base64;
    } 


    return "";
  }

  interface EditorProps {
    content: any;  
    type?: string;
    onChange: (content: any) => void;
  } 
const   Editor: React.FC<EditorProps> = ({content,onChange,type='md'})=>{
  // Creates a new editor instance.
  const editor = useCreateBlockNote({
    dictionary: locales.zh,
    schema, 
    // initialContent: content , 
   // @ts-ignore
    uploadFile
  });
 

  const inserts = [
    insertAlert(editor)
  ]


  
  async function markdownInputChanged() {  
    const blocks = await editor.tryParseMarkdownToBlocks(content); 
    editor.replaceBlocks(editor.document, blocks); 
  }

  async function initialContent(){ 
  
    try {
      // 确保 content 是一个有效的 PartialBlock[] 数组
      const parsedData = safeParse(content);
      if(editor && content){  
        editor.replaceBlocks(editor.document,parsedData);
      }
    } catch (error) {
      console.error("Error inserting blocks:", error);
    }
  }



  const handleChange = async () => { 
    const html = await editor.blocksToHTMLLossy(editor.document);
    const markdown = await editor.blocksToMarkdownLossy(editor.document);
   
    switch(type){
      case "md":
        onChange(markdown)
        break;
      case "json": 
        onChange(editor.document)
        break;
      case "html": 
        onChange(html)
        break;
    case "tn": 
        onChange(JSON.stringify(editor.document))
        break;
    }
   
  };

 
  useEffect(() => { 
    handleChange();  
      if(type ==="md"){
        markdownInputChanged()
      } 

      switch(type){
        case "md":
           markdownInputChanged();
           break;
        case "json": 
           initialContent();
           break;
        case "tn": 
           initialContent();
           break;
      }
  }, []);
  
  return  <BlockNoteView editor={editor} slashMenu={false} onChange={handleChange}>
  {/* Replaces the default Slash Menu. */}
  <SuggestionMenuController
    triggerCharacter={"/"}
    getItems={async (query) =>
      // Gets all default slash menu items and `insertAlert` item.
      filterSuggestionItems(
        [...getDefaultReactSlashMenuItems(editor),  ...inserts],
        query
      )
    }
  />
</BlockNoteView>;
} 
 

export default Editor